package com.example.wendao.view.ui.fragment;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.wendao.App;
import com.example.wendao.R;
import com.example.wendao.common.PageUtils;
import com.example.wendao.databinding.FragmentNewsListBinding;
import com.example.wendao.view.adapter.NewsListAdapter;
import com.example.wendao.viewmodel.NewsViewModel;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class NewsListFragment extends Fragment {


    private NewsViewModel newsViewModel;

    private FragmentNewsListBinding binding;

    private RecyclerView rv;

    private SwipeRefreshLayout srl;

    private NewsListAdapter adapter;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        newsViewModel = new ViewModelProvider(App.getInstance()).get(NewsViewModel.class);
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_news_list, container, false);
        rv = binding.rvNewsList;
        srl = binding.srlNewsList;
        adapter = new NewsListAdapter();

        PageUtils.initRecyclerView(rv, adapter, new LinearLayoutManager(getContext()));
        binds();
        newsViewModel.getAllNews().observe(this.getViewLifecycleOwner(), adapter::submitList);

        return binding.getRoot();
    }


    private void binds() {
        // 模拟下拉刷新
        srl.setOnRefreshListener(() -> {
            srl.setRefreshing(true);
            Observable.just(0)
                    .delay(1, TimeUnit.SECONDS)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnNext(i -> {
                        srl.setRefreshing(false);
                        adapter.submitList(null);
                        newsViewModel.getAllNews().observe(getActivity(), users -> adapter.submitList(users));
                    }).subscribe();
        });
    }

}